<!--
* @FileDescription:
-->
<template>
  <div class="PipCheck">
    <div class="ag-toolbar">
      <el-tooltip class="item" effect="dark" content="↺ Refresh Data">
        <el-button type="primary" @click="query" circle>
          <el-icon><Refresh /></el-icon>
        </el-button>
      </el-tooltip>
      <el-button type="primary" @click="dialogTableVisible = true"
        ><el-icon><Edit /></el-icon>井数据维护
      </el-button>
      <el-button type="primary" @click="dialogintervalVisible = true"
        ><el-icon><Calendar /></el-icon> 检管周期维护
      </el-button>
      <el-dialog
        title="📄井数据维护"
        destroy-on-close
        v-model="dialogTableVisible"
        draggable
        :before-close="dialogClosed"
      >
        <EditData></EditData>
      </el-dialog>
      <el-dialog
        title="🕘检管周期维护"
        draggable
        destroy-on-close
        v-model="dialogintervalVisible"
        :before-close="dialogClosed"
      >
        <CheckintervalDialog></CheckintervalDialog>
      </el-dialog>
    </div>
    <p class="report">{{ report }}</p>
    <div class="title">超过检管周期水井</div>
    <ag-grid-vue
      class="ag-theme-balham"
      :rowData="table_data"
      :columnDefs="query_columns"
      :enableRangeSelection="enableRangeSelection"
      :defaultColDef="defaultColDef"
      :onGridReady="onGridReady"
      style="width: 100%; height: 600px"
    ></ag-grid-vue>
    <button id="expoBtn" class="ag-btn" v-on:click="expotab()">
      <el-icon><Download /></el-icon>下载
    </button>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { dbquery } from "@/apis/query";
import columnsnorm from "@/apis/columnsnorm";
//import queryresnorm from "@/apis/queryresnorm";
import { AgGridVue } from "ag-grid-vue3";
//import PipAlertRenderer from "@/components/PipAlertRenderer.vue";
import { ref } from "vue";
import EditData from "@/components/EditData.vue";
import CheckintervalDialog from "@/components/CheckintervalDialog.vue";
var gridApi = null;
var gridColumnApi = null;
var table_data = ref([]);
var query_columns = ref([]);
var report = ref([]);
//var querying = {};
var dialogTableVisible = ref(false);
var dialogintervalVisible = ref(false);
//var query_result = null;
var defaultColDef = {
  sortable: true,
  resizable: true,
  editable: false,
  wrapText: true,
  autoHeight: true,
  filter: true,
};
const coldefs = {
  井号: {
    pinned: "left",
    filter: "agTextColumnFilter",
  },
  开发单元: {
    pinned: "left",
    filter: "agTextColumnFilter",
  },
  剩余天数: {
    filter: "agNumberColumnFilter",
    sort: "asc",
  },
  监控: {
    cellRenderer: (params) =>
      params.value < -365 ? "🔴 超1年" : params.value < 365 ? "🟡 " : "🟢",
  },
};
function onGridReady(params) {
  gridApi = params.api;
  gridColumnApi = params.columnApi;
  query();
}
function expotab() {
  gridApi.exportDataAsCsv({ fileName: "水井检管信息" });
}
function autoSizeAll() {
  gridColumnApi.autoSizeAllColumns(true);
}
function dialogClosed(done) {
  query(); //可优化
  done();
}
/*
function query() {
  report.value = "";
  //querying = true;
  var sql =
    "select injectionpip.`开发单元`,井号,if(是否内衬,'是','否') as 是否内衬,DATE_FORMAT(上次作业时间,'%Y-%m-%d') as 上次作业时间,if(是否内衬,内衬或防腐,普通)  as 检管周期 from pytrol.injectionpip join pytrol.checkinterval on injectionpip.`开发单元`=checkinterval.`开发单元` where 显示标记=1 ";
  console.log("query running");
  dbquery("dbpytrol", sql)
    .catch(async (err) => {
      ElMessage({
        message: err,
        type: "err",
      });
    })
    .then(async (result) => {
      if (result.data.err) {
        ElMessage({
          message: result.data.err + ":" + result.data.message,
          type: "error",
        });
      } else if (result.data.length == 0) {
        ElMessage({
          message: "井史数据为空",
          type: "warning",
        });
      } else {
        //query_result = JSON.parse(JSON.stringify(result.data));

        var temparray = [];
        var repnum = [result.data.length, 0, 0];
        result.data.forEach((array) => {
          var temp = array;
          temp["管柱入井时间"] = Math.round(
            (new Date() - new Date(array["上次作业时间"])) / 1000 / 60 / 60 / 24
          );
          temp["剩余天数"] = temp["检管周期"] - temp["管柱入井时间"];
          temp["监控"] = temp["剩余天数"];
          temparray.push(temp);
          if (temp["剩余天数"] < -365) repnum[1] = repnum[1] + 1;
          else if (temp["剩余天数"] < 0) repnum[2] = repnum[2] + 1;
          report.value = `目前监控水井总数 ${repnum[0]} 口，超过检管周期1年以上未检管井数 ${repnum[1]} 口，超过检管周期1年以内井数 ${repnum[2]} 口。`;
        });

        query_columns.value = columnsnorm(
          Object.keys(temparray[0]),
          ["field"],
          coldefs
        );
        table_data.value = temparray;
        //console.log(query_columns.value);
        console.log(table_data.value);
        //console.log("query done");
      }
    })
    .then(async () => {
      //autoSizeAll();
      gridApi.refreshCells();
      //querying = false;
    });
}
*/

function query() {
  report.value = "";
  //querying = true;
  var sql =
    "select injectionpip.`开发单元`,井号,if(是否内衬,'是','否') as 是否内衬,DATE_FORMAT(上次作业时间,'%Y-%m-%d') as 上次作业时间,if(是否内衬,内衬或防腐,普通)  as 检管周期 from pytrol.injectionpip join pytrol.checkinterval on injectionpip.`开发单元`=checkinterval.`开发单元` where 显示标记=1 ";
  console.log("query running");
  dbquery("dbpytrol", sql)
    .catch(async (err) => {
      ElMessage({
        message: err,
        type: "err",
      });
    })
    .then(async (result) => {
      if (result.data.err) {
        ElMessage({
          message: result.data.err + ":" + result.data.message,
          type: "error",
        });
      } else if (result.data.length == 0) {
        ElMessage({
          message: "井史数据为空",
          type: "warning",
        });
      } else {
        //query_result = JSON.parse(JSON.stringify(result.data));

        var temparray = [];
        var repnum = [result.data.length, 0, 0];
        result.data.forEach((array) => {
          var temp = array;
          temp["管柱入井时间"] = Math.round(
            (new Date() - new Date(array["上次作业时间"])) / 1000 / 60 / 60 / 24
          );
          temp["剩余天数"] = temp["检管周期"] - temp["管柱入井时间"];
          temp["监控"] = temp["剩余天数"];
          if (temp["剩余天数"] < -365) {
            repnum[1] = repnum[1] + 1;
            temparray.push(temp);
          } else if (temp["剩余天数"] < 0) {
            repnum[2] = repnum[2] + 1;
            temparray.push(temp);
          }
          report.value = `目前监控水井总数 ${repnum[0]} 口，已超检管周期 ${
            repnum[1] + repnum[2]
          } 口：其中超检管周期1年 以内 ${repnum[2]} 口，超检管周期1年 以上 ${
            repnum[1]
          } 口。`;
        });

        query_columns.value = columnsnorm(
          Object.keys(temparray[0]),
          ["field"],
          coldefs
        );
        table_data.value = temparray;
        //console.log(query_columns.value);
        //console.log(table_data.value);
        //console.log("query done");
      }
    })
    .then(async () => {
      //autoSizeAll();
      gridApi.refreshCells();
      //querying = false;
    });
}
</script>

<style scoped>
.ag-toolbar {
  margin-bottom: 5px;
}
.title {
  text-align: center;
  background-color: royalblue;
  font-weight: bolder;
  color: white;
}
.report {
  margin-bottom: 5px;
  font-weight: bolder;
}
#expoBtn {
  display: inline;
  float: right;
}
</style>
